package com.yztc.thinkpad.mandemo.single;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yztc.thinkpad.mandemo.R;
 import com.yztc.thinkpad.mandemo.single.base.BaseFragment;
import com.yztc.thinkpad.mandemo.single.bean.ContentBean;
import com.yztc.thinkpad.mandemo.single.bean.DataBean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import utils.Okhttputils;

/**
 * Created by meidou on 2016/10/6.
 */
public class SingleViewpagerFragment extends BaseFragment {
    @Bind(R.id.single_relativelayout)
    RecyclerView single_relativelayout;
    @Bind(R.id.single_fot)
    FloatingActionButton fot;
    @Bind(R.id.swip_single)
    SwipeRefreshLayout swip_single;
    private GridLayoutManager mManager;
    private DataBean mDataBean;
    private SingleRecyclerAdapter adapter;
    private  int pager=1;
    private int lastVisibleItem;
    private int mScrollThreshold;
    public void setScrollThreshold(int scrollThreshold) {
        mScrollThreshold = scrollThreshold;
    }
    private List<ContentBean.DataBean> mDataBeenlist = new ArrayList<>();
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(pager==1) {
                mDataBeenlist = (List<ContentBean.DataBean>) msg.obj;
                adapter = new SingleRecyclerAdapter(getContext(), getDataBean(), mDataBeenlist);
                single_relativelayout.setAdapter(adapter);
                lastVisibleItem = mManager.findLastVisibleItemPosition();
            }else {
                adapter.rush((List<ContentBean.DataBean>) msg.obj,false);
            }
        }
    };
    public DataBean getDataBean() {
        return mDataBean;
    }

    public void setDataBean(DataBean dataBean) {
        mDataBean = dataBean;
    }

    @Override
    protected void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String contenturl = "http://api.nanyibang.com/tuijian-product?age=24&cateId=";
                    String s = "&channel=yingyongbao&page=";
                    String pagered="&system_name=android&versionCode=219";
                    int  cateId =getDataBean().getClassID() ;
                    String contentjson = Okhttputils.getInstance().run(contenturl+cateId+s+pager+pagered);
                    String contentdata = JSONObject.parseObject(contentjson).getString("data");
                    List<ContentBean.DataBean> contentlist = new ArrayList<>();
                    contentlist = JSONArray.parseArray(contentdata,ContentBean.DataBean.class);
                    if(contentlist!=null) {
                        Message message = new Message();
           //             message.what = 0;
                        //message.obj = typrlist;
                        message.obj = contentlist;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    @Override
    protected void initView() {
        mManager = new GridLayoutManager(getContext(),6);
        mManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch ((adapter.getItemViewType(position))){
                    case 0:
                        return 6;//宽度为6， item满屏
                    case 1:
                        return 6;
                    default:
                        return 3;
                }
            }
        });
        single_relativelayout.setLayoutManager(mManager);

        //single_relativelayout.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.));

     //
        //   mTitleSingle.setText("-----"+getDataBean().getName()+"精选-----");
        if(getDataBean()!=null){
//            List<CategoriesBean> totalist =getDataBean().getCategories();
//            TypeAdapter typeAdapter = new TypeAdapter(getContext(),totalist );
//            mMygridviewHomeType.setAdapter(typeAdapter);
        }
        fot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mManager.scrollToPositionWithOffset(0,0);
            }
        });
        //滑动隐藏和显示FAB
        single_relativelayout.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    boolean isSignificantDelta = Math.abs(dy) > mScrollThreshold;
                    if (isSignificantDelta) {
                        if (dy > 0) {
                            onScrollUp();
                        } else {
                            onScrollDown();
                        }
                    }
                }

                private void onScrollDown() {

                    fot.setVisibility(View.VISIBLE);
                }

                private void onScrollUp() {
                    fot.setVisibility(View.GONE);
                }
            });
        refresh();

    }

    //刷新数据
    private void refresh() {
        //加载更多
        single_relativelayout.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(final RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
               // lastItemCount = manager.getItemCount();
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            if(mDataBeenlist.size()!=0) {
                                pager++;
                                SingleRecyclerAdapter.load_more_status = 0;
                                initData();
                            }else{
                                SingleRecyclerAdapter.load_more_status = 1;
                                initData();
                            }
                        }
                    });
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mManager.findLastVisibleItemPosition();
            }
        });
        //设置刷新时动画的颜色  可以设置4个
        swip_single.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light
        );
        //下拉刷新
        swip_single.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (pager == 1) {
                            initData();
                        }
                        swip_single.setRefreshing(false);
                    }
                });
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.single_viewpager;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        SingleRecyclerAdapter.load_more_status = 0;
    }
}
